import CryptoJS from 'crypto-js'
import { JSEncrypt } from 'jsencrypt'
/**
 * 创建密钥
 * @returns AES密钥
 */
export function createAesKey() {
  const expect = 16
  let aesKey = Math.random().toString(36).substr(2)
  while (aesKey.length < expect) {
    aesKey += Math.random().toString(36).substr(2)
  }
  aesKey = aesKey.substr(0, 16)
  return aesKey
}

/**
 * AES加密
 * @param {*} word 密文
 * @param {*} aesKey AES密钥
 * @returns
 */
export function AESEncrypt(word, aesKey) {
  aesKey = aesKey || 'abcdefgabcdefg12'
  var key = CryptoJS.enc.Utf8.parse(aesKey)// Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return encrypted.toString()
}

/**
 * AES解密
 * @param {*} word 密文
 * @param {*} aesKey AES密钥
 * @returns
 */
export function AESDecrypt(word, aesKey) {
  aesKey = aesKey || 'abcdefgabcdefg12'
  var key = CryptoJS.enc.Utf8.parse(aesKey)// Latin1 w8m31+Yy/Nw6thPsMpO5fg==
  //   var srcs = CryptoJS.enc.Utf8.parse(word)
  var encrypted = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 })
  return CryptoJS.enc.Utf8.stringify(encrypted).toString()
}

/**
 * RSA加密算法
 * @param {*} aesKey 未加密的AES密钥
 * @param publickey 公钥
 * @returns
 */
export function RSAEncrypt(aesKey, publickey) {
  let jse = new JSEncrypt()
  jse.setPublicKey(publickey)
  return jse.encrypt(aesKey)
}

/**
 * RSA解密算法
 * @param {*} aesKey 加过密的AES密钥
 * @param privateKey 私钥
 * @returns
 */
export function RSADecrypt(aesKey, privateKey) {
  let jse = new JSEncrypt()
  jse.setPrivateKey(privateKey)
  return jse.decrypt(aesKey)
}
